package com.yunmai.steplibrary;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.yunmai.steplibrary.utils.Log;

public class StepReceiver extends BroadcastReceiver {
  private final Context mContext;
  private final Runnable saveRunable;
  private final Runnable checkStepRunable;

  public StepReceiver(Context context, Runnable saveStepRunable,
      Runnable checkStepRunable) {
    this.mContext = context;
    this.saveRunable = saveStepRunable;
    this.checkStepRunable = checkStepRunable;
  }

  public void init() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    //关机广播
    filter.addAction(Intent.ACTION_SHUTDOWN);
    // 屏幕解锁广播
    filter.addAction(Intent.ACTION_USER_PRESENT);
    // 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
    // example：有时候会用到系统对话框，权限可能很高，会覆盖在锁屏界面或者“关机”对话框之上，
    // 所以监听这个广播，当收到时就隐藏自己的对话，如点击pad右下角部分弹出的对话框
    filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    //监听日期变化
    filter.addAction(Intent.ACTION_DATE_CHANGED);
    filter.addAction(Intent.ACTION_TIME_CHANGED);
    filter.addAction(Intent.ACTION_TIME_TICK);
    if (mContext != null) {
      mContext.registerReceiver(this, filter);
    }
  }

  public void unInit() {
    if (mContext != null) {
      mContext.unregisterReceiver(this);
    }
  }

  @Override public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    switch (action) {
      case Intent.ACTION_SCREEN_OFF://关机广播，保存好当前数据
      case Intent.ACTION_SHUTDOWN:
      case Intent.ACTION_USER_PRESENT:     // 屏幕解锁广播
      case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
        Log.debug("step","tubage:onReceive action action!"+action);

        // 当长按电源键弹出“关机”对话或者锁屏时系统会发出这个广播
        // example：有时候会用到系统对话框，权限可能很高，会覆盖在锁屏界面或者“关机”对话框之上，
        // 所以监听这个广播，当收到时就隐藏自己的对话，如点击pad右下角部分弹出的对话框
        saveRunable.run();
        break;
      case Intent.ACTION_DATE_CHANGED:
      case Intent.ACTION_TIME_CHANGED:
      case Intent.ACTION_TIME_TICK:
        Log.debug("step","tubage:onReceive timer change!");
        checkStepRunable.run();
       break;
    }
  }
}
